#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Software : PyCharm
# @Time    : 2024-12-18 11:06
# @Author  : gzh
# @File : TopTkParent.py

from tkinter import Toplevel, Label

class TopTkParent(Toplevel):
    def __init__(self, parent, title='', showT=True, ww=345, hh=206,
                 font=('Arial', 12, 'bold'), relh=0.1, width_draw=True):
        if width_draw:
            parent.withdraw()
        super().__init__(parent)
        self.wm_overrideredirect(True)
        self.wm_attributes("-topmost", True)
        ww = int(ww * parent.winfo_ki)
        hh = int(hh  * parent.winfo_ki)
        self.x_position = int((parent.now_w - ww) / 2)
        self.y_position = int((parent.now_h - hh) / 2)
        self.geometry(f'{ww}x{hh}+{self.x_position}+{self.y_position}')
        self._drag_data = {"x": 0, "y": 0, "is_dragging": False}
        self.grab_set()
        if showT:
            top_label = Label(self, text=title, font=font, bd=0, bg='#FFFFFF', fg='black',
                              anchor='w', justify='left')
            top_label.place(relx=0, rely=0, relwidth=1, relheight=relh)
            top_label.bind("<Button-1>", lambda event: self.on_titlebar_click(event))
            top_label.bind("<B1-Motion>", self.on_drag_motion)

    def on_titlebar_click(self, event):
        self._drag_data["x"] = event.x_root - self.winfo_rootx()
        self._drag_data["y"] = event.y_root - self.winfo_rooty()

    def on_drag_motion(self, event):
        x_new = event.x_root - self._drag_data["x"]
        y_new = event.y_root - self._drag_data["y"]
        self.geometry(f'{self.winfo_width()}x{self.winfo_height()}+{x_new}+{y_new}')

